#include "sensor.h"

// Prints out a given error.
void error(const char *msg) { perror(msg); }

// Sensor process. Sends data to repository.
void *sensor (void *t_id) {
  struct TDATA *tdata;
  int id = (int) t_id;
  int t, r, s = 0;
  int dest = PORT+RBEG+(id-SBEG)%NUM_REPOS;
  char data[BSIZE];

  tdata->dest = dest; 
  tdata->type = DATA; 
  while (true) {
    srand(t);
    usleep(rand());
    t = time(NULL);
    s = rand()%SPEED_RANGE + SPEED_MIN;
    r = rand()%NUM_ROADS;
    bzero(data, BSIZE);
    sprintf(data, "%d,%d,%d,%d,%d,%d,%d,\n",
     id,dest,DATA,id,t,r,s);
    tdata->src = id; 
    strcpy(tdata->msg, data); 
    // TODO: Create thread to send message.
     sender(tdata);
  }

  return;
}

// Create sensor threads; then wait until they all finish.
int main () {
  int i;
  pthread_t thread[NUM_TOTAL];
  for (i=SBEG; i<SEND; i++) pthread_create((pthread_t *) thread[i], NULL, sensor, (void *) i); 
  for (i=SBEG; i<SEND; i++) pthread_join((pthread_t *) thread[i], NULL);
  return 0;
}
